package com.edocbase.desktop.plugins.mdiary.figures;

import org.eclipse.draw2d.AbstractImageFigure;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Insets;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.swt.graphics.Image;

public class ThumbFigure extends AbstractImageFigure {
	private Image img;
	private Dimension size = new Dimension();

	public void setImage(Image image) {
		if (img == image)
			return;
		img = image;
		if (img != null)
			size = new Rectangle(image.getBounds()).getSize();
		else
			size = new Dimension();
		revalidate();
		notifyImageChanged();
		repaint();
	}

	@Override
	protected void paintFigure(Graphics graphics) {
		super.paintFigure(graphics);
		if (getImage() == null)
			return;

		int x, y;
		Rectangle area = getBounds().getCopy().shrink(getInsets().getHeight(),
				getInsets().getWidth());
		x = area.x;
		y = area.y;
		Dimension preSize = getPreferredSize();
		if (size.width < preSize.width || size.height < preSize.height) {
			x = x + (preSize.width - size.width) / 2;
			y = y + (preSize.height - size.height) / 2;
			graphics.drawImage(img, x, y);
		} else {
			//org.eclipse.swt.graphics.Rectangle imgSize = img.getBounds();
			//x = x + Math.abs((preSize.width - size.width) / 2);
			//y = y + Math.abs((preSize.height - size.height) / 2);
			Insets insets = getInsets();
			graphics.drawImage(img, 0, 0, size.width, size.height, x,y,
					preSize.width - insets.getWidth(), preSize.height);
		}
	}

	@Override
	public Image getImage() {
		return img;
	}
}
